package cn.yunhe.controller;

import cn.yunhe.entity.User;
import cn.yunhe.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/UserLoginServlet")

public class UserLoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("userName");
        String pwd=request.getParameter("passWord");
        User user=new User();
        user.setName(name);
        user.setPassword(pwd);
         HttpSession session=request.getSession();

        Map<String,Object> map=new HashMap<>();
        HttpSession sess=(HttpSession)map.get(name);
        if(sess!=null){
            User userSession= (User) ((HttpSession) sess).getAttribute("user");
            if(userSession.getState()==1){
                sess.invalidate();
                map.remove(name);
            }
        }
        UserService userService=new UserService();
        User user1=userService.userLogin(user);
        if(user1!=null){
            boolean flag=userService.userStateUpdate(user);
            if(flag){
                Cookie cookie=new Cookie(URLEncoder.encode(name,"UTF-8"),URLEncoder.encode(pwd,"UTF-8"));
                cookie.setMaxAge(60*60*24*5);
                response.addCookie(cookie);
                user1.setState(1);
                session.setAttribute("user",user1);
                map.put(name,session);
            }
            request.setAttribute("user",user1);
            request.getRequestDispatcher("index.jsp").forward(request,response);
        }else{

            response.sendRedirect("login.jsp");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
